package lab1;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class SubmitServlet
 */
@WebServlet("/SubmitServlet")
public class SubmitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SubmitServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// kiem tra tinh hop le cua cac du lieu dau vao, vi ban dau chua co du
		// lieu nen mac dinh la false
		boolean isValid = true;

		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String firstName = request.getParameter("firstname");
		String lastName = request.getParameter("lastname");
		boolean female = request.getParameter("sex").equalsIgnoreCase("Female");
		int year = 0;
		try {
			year = Integer.parseInt(request.getParameter("year"));
		} catch (NumberFormatException e) {
		}
		String industry = request.getParameter("industry");
		String jobTitle = request.getParameter("jobtitle");
		String company = request.getParameter("company");
		String city = request.getParameter("city");
		String telephone = request.getParameter("telephone");
		String[] favorites = request.getParameterValues("favorite");
		String desiredPlatform = request.getParameter("platform");

		if (firstName == null || firstName.equals("")) {
			isValid = false;
		}
		if (lastName == null || lastName.equals("")) {
			isValid = false;
		}
		if (email == null || email.equals("")) {
			isValid = false;
		}
		if (password == null || password.equals("")) {
			isValid = false;
		}

		if (isValid) {
			// if hop le: tao bean user
			User user = new User(firstName, lastName, email, password, female,
					year, industry, jobTitle, company, city, telephone,
					favorites, desiredPlatform);

			// Dat bean user vao pham vi request
			request.setAttribute("registeredUser", user);

			// forward toi trang welcome.jsp
			getServletContext().getRequestDispatcher("/lab1/Welcome.jsp")
					.forward(request, response);
		} else {
			getServletContext().getRequestDispatcher("/lab1/Regagain.jsp")
					.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
